package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.config.IniConfig;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 22_07设置终端工作参数
 * 模拟量表计类型及输出范围
 * 11byte,
 * 第 1 个字节： 模拟量表计通道号（从 1 开始）
 * 第 2 个字节： 表计类型， 0x00， 电压型； 0x01 电流型； 0x02 阴极保护测试桩；
 * 第 3~6 字节浮点数： 输出范围最小值（低字节在前）
 * 第 7~10 字节浮点数： 输出范围最大值（低字节在前）
 * 第 11 字节浮点数， 压力表供电电压
 * 第 12-15 字节浮点数： 基准电压
 * Created by zwz on 2020/6/22.
 */
public class Cmd_22_07Fragment extends BaseFragment {


    @BindView(R.id.sp_id)
    Spinner spId;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.edt_min)
    EditText edtMin;
    @BindView(R.id.edt_max)
    EditText edtMax;
    @BindView(R.id.sp_power)
    Spinner spPower;
    @BindView(R.id.edt_power)
    EditText edtPower;
    @BindView(R.id.edt_power_py)
    EditText edtPyPower;

    @BindView(R.id.cb_enalbe)
    CheckBox cbEnable;
    @BindView(R.id.edt_time)
    EditText edtTime;
    @BindView(R.id.edt_min_lc)
    EditText edtMinLc;
    @BindView(R.id.edt_max_lc)
    EditText edtMaxLc;

    public static Cmd_22_07Fragment newInstance() {
        Cmd_22_07Fragment fragment = new Cmd_22_07Fragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_22_07;
    }

    @Override
    protected void initView() {
        List<String> list_ids = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            list_ids.add(String.valueOf(i));
        }
        ArrayAdapter<String> idsAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, list_ids);
        spId.setAdapter(idsAdapter);
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, IniConfig.moNiLiangBiao_des);
        spType.setAdapter(typeAdapter);
        ArrayAdapter<String> powerAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, IniConfig.power_des);
        spPower.setAdapter(powerAdapter);

    }


    public String getSpID() {
        return String.format(Locale.CHINA, "%02d", Integer.parseInt(spId.getSelectedItem().toString()));
    }

    public String getSpType() {
        String data = IniConfig.moNiLiangBiao_data.get(spType.getSelectedItemPosition());
        return String.format(Locale.CHINA, "%02d", Integer.parseInt(data));
//        return String.format(Locale.CHINA, "%02d", AnalogScaleTypeConfig.getType(spType.getSelectedItem().toString()));
    }

    public String getSpPower() {
        int data = spPower.getSelectedItemPosition();
        data=data+1;
        Log.e("xxxxxxxx", data + "data");
//        return data;
        return String.format("%02d", data);
    }

    /**
     * 获取电压范围，低字节在前
     * @return
     */
    public String getEdtPowerMinAndMax() {
        String str_min = edtMin.getText().toString();
        String str_max = edtMax.getText().toString();
        if (str_min.isEmpty() || str_max.isEmpty()) {
            toastShow("请填写表计输出电压范围");
            return "";
        }
        float f_min = Float.parseFloat(str_min);
        float f_max = Float.parseFloat(str_max);

        if (f_min >= f_max) {
            toastShow("上限必须大于下限");
            return "";
        }
        return BleUtils.getFloat(f_min) + " " + BleUtils.getFloat(f_max);
    }

    /**
     * 获取电量程，低字节在前,max在前
     * @return
     */
    public String getEdtLCMinAndMax() {
        String str_min = edtMinLc.getText().toString();
        String str_max = edtMaxLc.getText().toString();
        if (str_min.isEmpty() || str_max.isEmpty()) {
            toastShow("请填写量程");
            return "";
        }
        float f_min = Float.parseFloat(str_min);
        float f_max = Float.parseFloat(str_max);

        if (f_min >= f_max) {
            toastShow("上限必须大于下限");
            return "";
        }
        return BleUtils.getFloat(f_max) + " " + BleUtils.getFloat(f_min);
    }


    /**
     * 获取基准电压
     * @return
     */
    public String getEdtPower() {
        String str_power = edtPower.getText().toString();
        if (str_power.isEmpty()) {
            toastShow("请填写基准电压");
            return "";
        }
        return BleUtils.getFloat(Float.parseFloat(str_power));

    }


    /**
     * 获取偏移电压
     * @return
     */
    public String getEdtPyPower() {
        String str_power = edtPyPower.getText().toString();
        if (str_power.isEmpty()) {
            toastShow("请填写偏移电压");
            return "";
        }
        return BleUtils.getFloat(Float.parseFloat(str_power));

    }

    /**
     * 获取供电时间
     * @return
     */
    public String getTime() {
        String str_power = edtTime.getText().toString();
        if (str_power.isEmpty()) {
            toastShow("请填写压力表供电时间");
            return "";
        }
        String data= String.format("%08x", Integer.parseInt(str_power)).toUpperCase();
//        return BleUtils.numToHex16(Integer.parseInt(str_power));
//        return BleUtils.getFloat(Float.parseFloat(str_power));

        data =
                data.substring(6, 8) + " " + data.substring(4, 6)+" " +
        data.substring(2, 4) + " " + data.substring(0, 2);//低字节在前
        return data;
    }


    private void set() {
        if (IniConfig.moNiLiangBiao_data.size() != IniConfig.moNiLiangBiao_des.size()) {
            toastShow("ini配置文件有误,模拟量表类型节点中代号与描述个数不一致");
            return;
        }
        if (IniConfig.power_data.size() != IniConfig.power_des.size()) {
            toastShow("ini配置文件有误,电压列表节点中电压值与电压个数不一致");
            return;
        }


        String id = getSpID();
        String type = getSpType();
        String min_max = getEdtPowerMinAndMax();
        if (min_max.isEmpty())
            return;
        String min_max_lc = getEdtLCMinAndMax();
        if (min_max_lc.isEmpty())
            return;

        //基准电压
        String referenceVoltage = getEdtPower();
        if (referenceVoltage.isEmpty())
            return;
        //偏移电压
        String pyPower = getEdtPyPower();
        if (pyPower.isEmpty())
            return;
        //供电时间
        String time = getTime();
        if (time.isEmpty())
            return;
        //供电电压
        String powerVoltage = getSpPower();


        String enable = cbEnable.isChecked() ? "AA" : "55";

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(CmdConfig.CMD_22_07).append(" ")
                .append(id).append(" ")//第 1 个字节：模拟量表计通道号（从1 开始）
                .append(type).append(" ")//第 2 个字节：表计类型
                .append(min_max).append(" ")
                .append(powerVoltage).append(" ")//压力表供电电压通道号
                .append(min_max_lc).append(" ")//量程
                .append(referenceVoltage).append(" ")//基准电压
                .append(pyPower).append(" ")//偏移电压
                .append(time).append(" ")//供电时间
                .append(enable);//电压


        sendData(stringBuilder.toString());
        Log.e("xxxxxxxxxx", stringBuilder.toString());
    }





    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_22, data);
        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();

                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_22)
                        && data[13].equals(CmdConfig.CMD_22_07)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }


    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }

    @OnClick({R.id.btn_set, R.id.btn_set_power})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_set:
                set();
                break;
            case R.id.btn_set_power:
                set2();
                break;
        }
    }
    private void set2() {
        //基准电压
        String referenceVoltage = getEdtPower();
        if (referenceVoltage.isEmpty())
            return;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(CmdConfig.CMD_22_04).append(" ")
                .append(referenceVoltage); //基准电压;

        sendData(stringBuilder.toString());

    }
}
